<?php

/**
 * GalleryController
 * 
 * @author andrew
 * @version 1.0
 */

class Gallery_PhotoController extends Zend_Controller_Action {
	/**
	 * Вывод всех фотографий
	 */
	public function indexAction() {
		$page = $this->_request->getParam('page',0);
		
		$resultsPerPage = 10;
		
		$query = Doctrine_Query::create()
				 ->from('Gallery_Model_Photo')
				 ->orderBy('id DESC');
				 
		$pager = new Doctrine_Pager($query, $page, $resultsPerPage);
		
		$pagerRange = new Doctrine_Pager_Range_Sliding(array('chunk' => 5));
		
		$pageLayout = new Doctrine_Pager_Layout($pager, $pagerRange, '/admin/gallery/{%page_number}');
		
		$pageLayout->setTemplate('&nbsp;<a href="{%url}" class="paginator">{%page}</a>&nbsp;');
		$pageLayout->setSelectedTemplate('[<b class="selectPage">{%page}</b>]');
		$paginator = $pageLayout->getPager();
		
		$this->view->photos = $pageLayout->execute();
		$this->view->paginator = $this->view->translate('Page: ') . $pageLayout->display('',true) . ' ' . 
								 $this->view->translate('Total items: ') . $paginator->getNumResults();
	}
	
	/**
	 * Редактирование фотографии
	 */
	public function updateAction() {
		$id = $this->_request->getParam('id',0);
		
		$photo = Doctrine_Core::getTable('Gallery_Model_Photo')->find($id);
		
		if(!$id || !$photo)
			throw new Zend_Controller_Action_Exception('Photo not found!', 404);
		
		$form = new Gallery_Form_Photo();
		$form->setAction($this->view->url(array('id' => $id),'gallery_photo_update'));
		
		$populate = array(
			'published' => $photo->published,
		);
		
		$locales = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOption('locales');
		
		foreach ($locales as $lang=>$value) {
			$populate['name'][$lang] = $photo->Translation[$lang]->name;
		}
		
		if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
			$values = $form->getValues();
			$file = $form->photo->getFileInfo();
			
			if($file['photo']['error'] == 0) {
				//если файл загружен без ошибок
								
				$ext = split("[/\\.]", $file['photo']['name']);
				$newName =  'photo_' . md5(time()) . '.' . $ext[count($ext)-1];
				
				$factoryImage = ZFEngine_Image::factory(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $file['photo']['name']);
				$factoryImage->saveAs(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $newName, 90);
				$factoryImage->resize(480, 320, true);
				$factoryImage->saveAs(APPLICATION_PATH . "/../upload/media/pictures/gallery/medium/" . $newName, 90);
				$factoryImage->resize(120, 120, true);
				$factoryImage->saveAs(APPLICATION_PATH . "/../upload/media/pictures/gallery/small/" . $newName, 90);
				
				unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $file['photo']['name']);
				
				unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $photo->photo);
				unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/small/" . $photo->photo);
				unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/medium/" . $photo->photo);
				
				$photo->photo = $newName;
			}
			
			foreach ($values['name'] as $lang=>$value) {
				$photo->Translation[$lang]->name = $value;	
			}
			
			$photo->published = $values['published'];
			$photo->save();
			
			$this->_helper
				     ->getHelper('FlashMessenger')
					 ->addMessage($this->view->translate('Photo has been save successfully!'));
				 
			return $this->_redirect($this->view->url(array(),'gallery_photo_index'));
			
		} else {
			$form->populate($populate);
			$imagePreview = $form->createElement('image', 'image_preview');
			$imagePreview->setLabel($this->view->translate('Image Preview:'));
			
			$sizePhoto = getimagesize(APPLICATION_PATH . '/..//upload/media/pictures/gallery/small/' . $photo->photo);
			$imagePreview->setAttrib('style', 'width:' . $sizePhoto[0] . 'px;height:' . $sizePhoto[1] . ';');
			
			$imagePreview->setAttrib('onclick', 'return false;');
			$imagePreview->setOrder(1);
			$imagePreview->setImage("/upload/media/pictures/gallery/small/" . $photo->photo);
			$form->addElement($imagePreview);
		}
		
		$this->view->form = $form;
	}
	
	/**
	 * Создание фотографии
	 */
	public function createAction() {
		$form = new Gallery_Form_Photo();
		$form->setAction($this->view->url(array(),'gallery_photo_create'));
		
		$photo_element = $form->getElement('photo');
		$photo_element->setRequired(true);
		
		if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
			$values = $form->getValues();
			
			$file = $form->photo->getFileInfo();
			
			if($file['photo']['error'] == 0) {
				//если файл загружен без ошибок
				$ext = split("[/\\.]", $file['photo']['name']);
				$newName =  'photo_' . md5(time()) . '.' . $ext[count($ext)-1];
				
				$factoryImage = ZFEngine_Image::factory(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $file['photo']['name']);
				$factoryImage->saveAs(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $newName, 90);
				$factoryImage->resize(480, 320, true);
				$factoryImage->saveAs(APPLICATION_PATH . "/../upload/media/pictures/gallery/medium/" . $newName, 90);
				$factoryImage->resize(120, 120, true);
				$factoryImage->saveAs(APPLICATION_PATH . "/../upload/media/pictures/gallery/small/" . $newName, 90);
				
				unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $file['photo']['name']);
				
				$photo = new Gallery_Model_Photo();
				
				foreach ($values['name'] as $lang=>$value) {
					$photo->Translation[$lang]->name = $value;	
				}
				
				$photo->published = $values['published'];
				$photo->photo = $newName;
				$photo->save();
				
				$this->_helper
				     ->getHelper('FlashMessenger')
					 ->addMessage($this->view->translate('Photo has been save successfully!'));
				 
				return $this->_redirect($this->view->url(array(),'gallery_photo_index'));	
				
			} else {
				$this->_helper
				     ->getHelper('FlashMessenger')
					 ->addMessage($this->view->translate('Error with upload photo!'));
				 
				return $this->_redirect($this->view->url(array(),'gallery_photo_create'));
			}
		}
		
		$this->view->form = $form;
	}
	
	/**
	 * Удаление фотографии
	 */
	public function deleteAction() {
		$id = $this->_request->getParam('id',0);
		
		$photo = Doctrine_Core::getTable('Gallery_Model_Photo')->find($id);
		
		if(!$id || !$photo)
			throw new Zend_Controller_Action_Exception('Photo not found!', 404);
		
		unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/original/" . $photo->photo);
		unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/medium/" . $photo->photo);
		unlink(APPLICATION_PATH . "/../upload/media/pictures/gallery/small/" . $photo->photo);
		$photo->delete();
		$this->_helper
			     ->getHelper('FlashMessenger')
				 ->addMessage($this->view->translate('Photo has been delete successfully!'));
		return $this->_redirect($this->view->url(array(),'gallery_photo_index'));
	}
	
	/**
	 * 
	 * Управление публикацией фотографии
	 */
	public function publishAction() {
		if($this->_request->isXmlHttpRequest()) {
			// Отключаем авторендеринг шаблонов
			$this->_helper->viewRenderer->setNoRender();
			// Отключаем шаблоны
			$this->_helper->layout()->disableLayout();
		
			$id = $this->_request->getParam('id',0);
			
			$photo = Doctrine_Core::getTable('Gallery_Model_Photo')->find($id);
			
			if(!$id || !$photo)
				throw new Zend_Controller_Action_Exception('Photo not found!', 404);
				
			if($photo->published) {
				$photo->published = false;
				$response_txt = false;
			} else {
				$photo->published = true;
				$response_txt = true;
			}
			$photo->save();
			$response = $this->getResponse();
			$response->appendBody($response_txt)->setHeader('content-type', 'text/plain', true);
		} else {
			return $this->_redirect($this->view->url(array(), 'gallery_photo_index'));
		}
	}

}
